import "DPI-C" function longint mem_read( input longint raddr , input bit is_icache);
import "DPI-C" function void mem_write( input longint waddr, input longint wdata, input byte wmask);
module axi_mem(
//AXI-Lite interface
  //global
  input ACLK,
  input ARESETn,
  //write addr
  input [63:0] AWADDR,
  input [2:0] AWPROT,
  input AWVALID,
  output AWREADY,
  //write data
  input [63:0] WDATA,
  input [7:0] WSTRB,
  input WVALID,
  output WREADY,
  //write response
  output [1:0] BRESP,
  output BVALID,
  input BREADY,
  //read addr
  input [63:0] ARADDR,
  input [2:0] ARPROT,
  input ARVALID,
  output ARREADY,
  //read data
  output [63:0] RDATA,
  output [1:0] RRESP,
  output RVALID,
  input RREADY
  

);

  localparam RESP_OKAY = 2'b00;
  // localparam RESP_EXOKAY = 2'b00;
  // localparam RESP_SLVERR = 2'b00;
  // localparam RESP_DECERR = 2'b00;

  assign AWREADY = 1'b1;
  assign WREADY = 1'b1;
  assign ARREADY = 1'b1;
  assign BRESP = RESP_OKAY;
  assign RRESP = RESP_OKAY;

  wire inst_write = AWPROT[2];
  wire inst_read = ARPROT[2];

  reg [63:0] waddr,raddr,rdata;
  reg bvalid,rvalid;
  localparam CNT_W = 3;
  reg [CNT_W-1:0] cnt;
  reg arvalid;
  always @(posedge ACLK) begin
    if(!ARESETn) begin
      waddr <= 64'b0;
      raddr <= 64'b0;
      bvalid <= 1'b0;
      rvalid <= 1'b0;
      rdata <= 64'b0;
      cnt <= {CNT_W{1'b0}};
    end else begin
      rdata <= 64'b0;
      cnt <= cnt + {{(CNT_W-1){1'b0}},1'b1};;
      // cnt <= {CNT_W{1'b0}};/*注释此行启用0-7周期随机访存延迟*/
      if(BREADY) bvalid <= 1'b0;
      if(WVALID) bvalid <= 1'b1;
      if(RREADY) rvalid <= 1'b0;
      if(ARVALID) begin 
        arvalid <= 1'b1;
        raddr <= ARADDR;
      end
      if((arvalid)&&(cnt=={CNT_W{1'b0}})) begin 
        rdata <= mem_read(raddr,inst_read);
        rvalid <= 1'b1;
        arvalid <= 1'b0;
      end
      if(AWVALID) waddr <= AWADDR;
      if(WVALID) mem_write(waddr,WDATA,WSTRB);
      
      
    end
  end
  assign BVALID = bvalid;
  assign RDATA = rdata;
  assign RVALID = rvalid;
endmodule
